# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import logging

from coin.exchange.util.feed_checker.types import FeedCheckerState


class BootupChecker(object):
  def __init__(self, *, bootup_time, timestamp, logger=None):
    self._bootup_time = bootup_time
    self._initialized_at = timestamp
    self._valid = True
    self._max_book_count = 0
    self._enabled = self._bootup_time > 0
    self._logger = logger or logging.getLogger(__name__)

  def _invalidate(self, *, timestamp):
    self._logger.warning('Bootup failed for %.2f > %.2f sec.',
                         (timestamp - self._initialized_at) * 1e-9,
                         self._bootup_time * 1e-9)
    self._valid = False

  def _is_initializing(self, *, timestamp):
    return self._enabled and timestamp - self._initialized_at < self._bootup_time

  def check_state(self, *, timestamp):
    if not self._valid:
      return FeedCheckerState.INVALID
    if not self._enabled:
      return FeedCheckerState.READY
    if self._is_initializing(timestamp=timestamp):
      return FeedCheckerState.INITIALIZING

    self._invalidate(timestamp=timestamp)
    return FeedCheckerState.INVALID

  def update_book_count(self, *, book_count, timestamp):
    if not self._valid or not self._enabled:
      return

    if self._is_initializing(timestamp=timestamp):
      if book_count > self._max_book_count:
        self._max_book_count = book_count
      if self._max_book_count > 1:
        self._enabled = False
    else:
      self._invalidate(timestamp=timestamp)
